package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.device.model.response.DeviceVO;
import com.wing.device.service.DeviceService;
import com.wing.product.model.entity.ProcessDevice;
import com.wing.product.model.entity.ProcessLineTemplate;
import com.wing.product.model.entity.ProductItem;
import com.wing.product.model.request.ProcessDeviceAddForm;
import com.wing.product.model.request.ProcessDeviceForm;
import com.wing.product.model.response.ProcessDeviceVO;
import com.wing.product.model.response.ProcessInfoVO;
import com.wing.product.service.ProcessDeviceService;
import com.wing.product.service.ProcessLineTemplateRecordService;
import com.wing.product.service.ProcessLineTemplateService;
import com.wing.product.service.ProductItemService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 工艺线路模板Controller
 *
 * @author xiayang
 */
@Validated
@Api(value = "Admin-管理", tags = "#/product/processLineTemplate")
@RestController("processLineTemplateController")
@RequestMapping("product/admin/processLineTemplate")
@RequiredArgsConstructor
public class ProcessLineTemplateController {

    private final ProcessLineTemplateService processLineTemplateService;
    private final ProcessLineTemplateRecordService processLineTemplateRecordService;
    private final ProductItemService productItemService;


    @ApiOperation(value = "查询所有", notes = "搜索")
    @GetMapping("/list")
    public PageResult<ProcessLineTemplate> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            String processLineType, String code, String name) {
        Page<ProcessLineTemplate> pg = new Page<>(page, limit);
        Map<String,Object> queryParam = new HashMap();
        queryParam.put("processLineType", processLineType);
        queryParam.put("code", code);
        queryParam.put("name", name);
        IPage<ProcessLineTemplate> list = processLineTemplateService.list(pg, queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(ProcessLineTemplate processLineTemplate) {
        List<ProcessLineTemplate> processLineTemplatelist = processLineTemplateService.list();
        ProcessLineTemplate result = processLineTemplatelist.stream().filter(t -> t.getName().equals(processLineTemplate.getName())).findFirst().orElse(null);
        if (result != null) {
            return JsonResult.fail("添加失败:工艺线路名称已存在");
        }
        if (processLineTemplateService.save(processLineTemplate)) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "查询模板关联的工艺", notes = "搜索")
    @GetMapping("/listAndProcess")
    public PageResult<ProcessInfoVO> listAndProcess(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit,
            @RequestParam("templateId") String templateId,
            String type,
            String sort,
            String order,
            String processType,
            String processNature,
            String processName,
            String processCode
            ) {
        Page<ProcessInfoVO> pg = new Page<>(page, limit);
        Map<String,Object> queryParam = new HashMap();
        queryParam.put("templateId", templateId);
        queryParam.put("type", type);
        queryParam.put("processType", processType);
        queryParam.put("processNature", processNature);
        queryParam.put("processName", processName);
        queryParam.put("sort", sort);
        queryParam.put("order", order);
        queryParam.put("processCode", processCode);
        IPage<ProcessInfoVO> list = processLineTemplateService.listAndProcess(pg, queryParam);
        //将查询出的对象根据序号排序
        if (CollectionUtil.isNotEmpty(list.getRecords())){
            for (ProcessInfoVO record : list.getRecords()) {
                if (ObjectUtil.isNull(record.getSortNumber())){
                    record.setSortNumber(0);
                }
                QueryWrapper<ProductItem> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("process_id",record.getId());
                queryWrapper.eq("is_deleted",false);
                List<ProductItem> productItems = this.productItemService.list(queryWrapper);
                record.setProductItems(productItems);
            }


            List<ProcessInfoVO> collect = list.getRecords().
                    stream().sorted(Comparator.comparingInt(ProcessInfoVO::getSortNumber)).
                    collect(Collectors.toList());
            return new PageResult<>(collect, list.getTotal());

        }
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "修改", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(ProcessLineTemplate processLineTemplate) {
        if (processLineTemplateService.updateById(processLineTemplate)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping("/delete/{processLineTemplateId}")
    public JsonResult delete(@PathVariable("processLineTemplateId") Long processLineTemplateId) {
        if (processLineTemplateService.deleteById(processLineTemplateId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "删除模板绑定的工序", notes = "删除模板工序")
    @DeleteMapping("/deleteTempForProcess")
    public JsonResult deleteTempForProcess(Long processLineTemplateId,Long processId) {
        if (processLineTemplateService.deleteTempForProcess(processLineTemplateId,processId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

}
